package com.example.lirisheng.springbootfinalexperiment.util;


import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;



@Component
public class Jcode2SessionUtil {



    /**
     * 请求微信后台获取用户数据
     * @param code wx.login获取到的临时code
     * @return 请求结果
     * @throws Exception
     */

    // 请求的网址
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public static String jscode2session(String appid,String secret,String code,String grantType)throws Exception{
        //定义返回的json对象
//        JSONObject result = new JSONObject();
        //创建请求通过code换取session等数据
        HttpPost httpPost = new HttpPost(WX_LOGIN_URL);
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        //建立一个NameValuePair数组，用于存储欲传送的参数
        params.add(new BasicNameValuePair("appid",appid));
        params.add(new BasicNameValuePair("secret",secret));
        params.add(new BasicNameValuePair("js_code",code));
        params.add(new BasicNameValuePair("grant_type",grantType));
        //设置编码
        //添加参数
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse response=new DefaultHttpClient().execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
             //微信授权登录成功
            return EntityUtils.toString(response.getEntity());
        }
        throw  new Exception("抛出异常") ;

    }


}
